﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPF.BytesIO.TCPServer.ModelViews;
using STTech.BytesIO.Tcp;
using WPF.BytesIO.TCPServer.Models;
using System.Windows.Markup;
using STTech.BytesIO.Core;

namespace WPF.BytesIO.TCPServer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainViewModel ViewModel { get { return App.MainViewModel; } }


        private TcpServer _tcpServer;
        public MainWindow()
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen;

            InitializeComponent();


            this.Loaded += delegate
            {
                this.DataContext = ViewModel;

                _tcpServer = new TcpServer();
               
            };

        }

        private void _tcpServer_ClientDisconnected(object sender, ClientDisconnectedEventArgs e)
        {
            Print($"客户端[{e.Client.Host}:{e.Client.Port}]断开连接!", MyBrushes.Red);
            e.Client.OnDataReceived -= Client_OnDataReceived;
        }

        private void _tcpServer_ClientConnected(object sender, ClientConnectedEventArgs e)
        {
            Print($"客户端[{e.Client.Host}:{e.Client.Port}]连接成功!",MyBrushes.Green);

            e.Client.OnDataReceived += Client_OnDataReceived;
            //e.Client.UseHeartbeatTimeout(3000);
            e.Client.SendAsync(Encoding.UTF8.GetBytes("Connect Ok"));
        }

        private void Client_OnDataReceived(object sender, STTech.BytesIO.Core.DataReceivedEventArgs e)
        {
            TcpClient tcpClient = (TcpClient)sender;
            Print($"来自客户端[{tcpClient.RemoteEndPoint}]的消息：{e.Data.EncodeToString("GBK")}",MyBrushes.Green);

            tcpClient.SendAsync(Encoding.UTF8.GetBytes("Server yi jie shou！"));
        }

        private void _tcpServer_Closed(object sender, EventArgs e)
        {
            Print("服务器已停止！", MyBrushes.Red);
        }

        private void _tcpServer_Started(object sender, EventArgs e)
        {
            Print("服务器已打开", MyBrushes.Green);
        }

        private void btnStartListen_OnClick(object sender, RoutedEventArgs e)
        {
            
            if (ViewModel.TestInfo.ServerPort == 0)
            {
                Print("Port不能为空！", MyBrushes.Red);
                return;
            }

            if (!_tcpServer.IsListening)
            {
                _tcpServer.Port = ViewModel.TestInfo.ServerPort;
                _tcpServer.Started += _tcpServer_Started;
                _tcpServer.Closed += _tcpServer_Closed;
                _tcpServer.ClientConnected += _tcpServer_ClientConnected;
                _tcpServer.ClientDisconnected += _tcpServer_ClientDisconnected;

                _tcpServer.ClientConnectionAcceptedHandle = (s, a) =>
                {
                    if (_tcpServer.Clients.Count() < 1)
                    {
                        return true;
                    }
                    else
                    {
                        Print($"服务器已满,关闭客户端[{a.ClientSocket.RemoteEndPoint}]的连接！", MyBrushes.Red);
                        return false;
                    }
                };

                _tcpServer.StartAsync();
                Print("开始监听！", MyBrushes.Blue);
            }
            else
            {
                Print("监听中。。。,请勿再打开", MyBrushes.Red);
            }
        }

        private void btnStopListen_OnClick(object sender, RoutedEventArgs e)
        {
            Print("停止监听！",MyBrushes.Red);
            _tcpServer.StopAsync();
            _tcpServer.Started -= _tcpServer_Started;
            _tcpServer.Closed -= _tcpServer_Closed;
            _tcpServer.ClientConnected -= _tcpServer_ClientConnected;
            _tcpServer.ClientDisconnected -= _tcpServer_ClientDisconnected;
        }

        private Block Print(string data,MyBrushes statusBrush)
        {
            Block block = null;

            if (this.Dispatcher.Thread == System.Threading.Thread.CurrentThread)
            {
                block = GetBlock(data, statusBrush);

                this.rtxtLogName.Document.Blocks.Add(block);
            }
            else
            {
                this.Dispatcher.Invoke((Action)delegate
                {
                    block = Print(data, statusBrush);
                });
            }

            return block;
        }
        private Block GetBlock(string data, MyBrushes statusBrush)
        {
            Inline inline = new Run(data);

            inline.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(statusBrush.ToBrushString()));

            return new Paragraph(inline) { LineHeight = 1.0 };
        }
        private void tbnCleanRickTextBoxContent_OnClick(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.Invoke(() =>
            {
                rtxtLogName.Document.Blocks.Clear();
            });
        }
    }
}
